package com.demarc.pesquisas.web.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang3.StringUtils;

@FacesConverter(value = "EnumConverter")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class EnumConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) throws ConverterException {

		Enum object = null;
		Class enumType = component.getValueExpression("value").getType(
				context.getELContext());
		if (!StringUtils.isEmpty(value)) {
			object = Enum.valueOf(enumType, value);
		}
		return object;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object object) throws ConverterException {

		String retorno = null;
		if (object instanceof Enum) {
			Enum<?> type = (Enum<?>) object;
			retorno = type.toString();
		}
		return retorno;
	}
}
